const path = require("path");
const { exec } = require("child_process");

const { clone, pull, checkout, pushHead, getBranchs } = require("./git");

const runShell = require("./runShell");

// REPOS——path
const reposPath = path.resolve(__dirname, "./../.templateRepo");
// gp27-template-list
const targetPath = `${reposPath}/gp27-template-list`;
// gp27-template-list-git-repo
const gp27Url = `https://gitee.com/melody-lx/gp27-template-list.git`;
/**
 * @description: 删除store内容
 * @param {*}
 * @return {*}
 */

const removeCacheDir = () => {
  return new Promise((resolve, reject) => {
    exec(
      `rm -rf ${targetPath}`,
      {
        cwd: process.cwd(),
      },
      (err, stidio) => {
        if (err) {
          reject(err);
        } else {
          resolve(stidio);
        }
      }
    );
  });
};

// const cdTarget = (target) => runShell(`cd ${target}`);

class StoreContrulor {
  constructor() {
    this.current = {};
  }
  async init() {
    try {
      try {
        await pull();
      } catch (_error) {
        await removeCacheDir();
        await clone(`${gp27Url}`);
      }
    } catch (error) {
      await runShell(`mkdir .templateRepo`, path.resolve(__dirname, '../'))  
      await clone(`${gp27Url}`);
    }
    const branchList = await getBranchs();
    this.current = branchList;
    return branchList;
  }
}

module.exports = new StoreContrulor();
